package vn.wallet.app.managedBean;

import java.io.IOException;
import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.application.NavigationHandler;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import vn.wallet.app.domain.User;
import vn.wallet.app.helper.AppUtils;
import vn.wallet.app.helper.PageUtils;
import vn.wallet.app.helper.exceptions.TechnicalException;
import vn.wallet.app.service.IUserService;

@ManagedBean(name = "secureUser")
@SessionScoped
public class SecureUserBean implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private final Logger log = Logger.getLogger(this
			.getClass());
	private String username = "admin";
	private String password = "admin";

	private final String LOGIN_URL = AppUtils.LOGIN_URL;
	private final String LOGINED_SUCCESS_URL = AppUtils.LOGINED_SUCCESS_URL;

	@ManagedProperty(value = "#{userService}")
	IUserService userService;

	@ManagedProperty(value = "#{siteConfig}")
	SiteConfigBean siteConfig;

	// -----------------------------------------properties

	public String login() {
		FacesContext context = FacesContext.getCurrentInstance();
		FacesMessage msg = new FacesMessage("Login failed");
		msg.setSeverity(FacesMessage.SEVERITY_ERROR);

		try {
			String ipLogined = AppUtils.getRequestIp();
			System.out.println("ipLogined: " + ipLogined);
			User user = userService.validateUserLogin(username, password,
					ipLogined);
			if (user != null) {

				if (!user.isEmailConfirm()) {
					PageUtils.logFailed("Email has not confirmed");
				} else if (!user.isStatus()) {
					PageUtils.logFailed("User locked");
				} else {
					PageUtils.logSuccess("Login successfully");
					context.getExternalContext().getSessionMap()
							.put(AppUtils.USER_LOGINED_SESSION_NAME, user);
					siteConfig.setCurrentUser(user);

					FacesContext.getCurrentInstance().getExternalContext()
							.redirect(LOGINED_SUCCESS_URL);
				}
			} else {
				context.addMessage(null, msg);
			}
		} catch (Exception ex) {
			msg.setDetail(ex.getMessage());
			context.addMessage(null, msg);
		}
		return null;
	}

	public String logout() {
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		if (session != null) {
			session.invalidate();
		}
		try {
			FacesContext.getCurrentInstance().getExternalContext()
					.redirect(LOGIN_URL);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void validateSession() {
		FacesContext context = FacesContext.getCurrentInstance();
		Object obj = context.getExternalContext().getSessionMap()
				.get(AppUtils.USER_LOGINED_SESSION_NAME);

		try {
			if (!(obj instanceof User && obj != null)) {
				NavigationHandler navHandler = context.getApplication()
						.getNavigationHandler();
				navHandler.handleNavigation(context, null, LOGIN_URL
						+ "expired=true");
			} else {
				throw new TechnicalException("No user found");
			}
		} catch (Exception ex) {
			log.error(ex.getMessage(), ex);
		}
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public IUserService getUserService() {
		return userService;
	}

	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	public SiteConfigBean getSiteConfig() {
		return siteConfig;
	}

	public void setSiteConfig(SiteConfigBean siteConfig) {
		this.siteConfig = siteConfig;
	}
}
